<template>
	<view class="bank-card">
		<view v-if="!isEdit">
			<u-swipe-action @click="handleDel" :options="options">
				<view class="bank-card-detail">
					<view class="nameBox">
						<view class="user-name">
							{{bankCardObj.accountName || ''}} {{bankCardObj.mobile || ''}}
						</view>
					</view>
					<view class="detail-item">
						{{bankCardObj.bankName || ''}}
					</view>
					<view class="detail-item" v-if="bankCardObj.cardNo">
						{{bankCardObj.cardNo.slice(0,6)+'****'+bankCardObj.cardNo.substring(bankCardObj.cardNo.length-4)|| ''}}
					</view>
					<view class="detail-item">
						<view class="item-left">
							{{bankCardObj.adCodeName+bankCardObj.openAccBank || ''}}
						</view>
					</view>
					<view class="detail-item ">
						{{bankCardObj.bankCode || ''}}
					</view>
					<view class="detail-edit" @click="handleEdit">
						修改
					</view>
				</view>
			</u-swipe-action>
		</view>
		<view class="bank-card-add" v-else>
			<u-form :model="form" ref="uForm" label-width="250">
				<u-form-item label="卡号:" prop="cardNo" required>
					<u-input v-model="form.cardNo" placeholder="请点击图表识别银行卡信息" />
					<u-icon name="camera-fill" @click="handleCamera"></u-icon>
				</u-form-item>
				<u-form-item label="银行:" prop="bankName" required>
					<u-input v-model="form.bankName" placeholder="请识别" />
				</u-form-item>
				<u-form-item label="开户支行区域:" prop="adCodeName" required>
					<u-input v-model="form.adCodeName" type="select" @click="showPicker" placeholder="请选择所在地区" />
				</u-form-item>
				<u-form-item label="开户支行:" prop="openAccBank" required>
					<u-input v-model="form.openAccBank" placeholder="请输入开户支行" />
				</u-form-item>
				<u-form-item label="账户名:" prop="accountName" required>
					<u-input v-model="form.accountName" placeholder="请输入账户名" />
				</u-form-item>
				<u-form-item label="银行行号:" prop="bankCode" required>
					<u-input v-model="form.bankCode" placeholder="请输入银行行号" />
				</u-form-item>
				<u-form-item label="预留手机号:" prop="mobile" required>
					<u-input v-model="form.mobile" placeholder="请输入预留手机号" />
				</u-form-item>
				<u-form-item label="验证码:" prop="msgCode" required>
					<u-input v-model="form.msgCode" placeholder="请输入验证码" />
					<view class="ver-btn" @click="handleVerCode">
						{{VerCodeStr}}
					</view>
				</u-form-item>
			</u-form>
			<view class="detail-save" @click="save">
				添加银行卡
			</view>
		</view>
		<m-city :provinceData="list" headTitle="区域选择" ref="cityPicker" @funcValue="getpickerParentValue" pickerSize="3">
		</m-city>
	</view>
</template>

<script>
	import api from "@/config/api.js";
	import {
		getBankCard,
		saveBankCard,
		delBankCard,
		sendVerCode,
		distinguishBankCard
	} from '@/api/invoiceAndBankCard'
	import gkcity from "@/components/m-city/m-city.vue";
	import storage from "@/utils/storage.js";
	export default {
		components: {
			"m-city": gkcity,
		},
		data() {
			return {
				options: [{
					text: '删除',
					style: {
						color: "#FF2929",
						"font-size": "20px",
						backgroundColor: '#DBDBDB'
					}
				}],
				bankCardObj: {
					// bankName: "浦发银行",
					// cardNo: "6228483355445668412235",
					// openAccBank: "浦发银行上海枫叶路支行",
					// accountName: "盛乐",
					// mobile: "13155555555"
				},
				isEdit: false,
				form: {
					bankName: "",
					cardNo: "",
					openAccBank: "",
					accountName: "",
					mobile: "",
					msgCode: "",
					adCode: '', //省市区的code
					adCodeName: '', //省市区对应的名称
					bankCode: '', //银行行号
				},
				rules: {
					cardNo: [{
						required: true,
						message: '请识别银行卡',
						trigger: ['change', 'blur'],
					}],
					bankName: [{
						required: true,
						message: '请识别银行卡',
						trigger: ['change', 'blur'],
					}],
					adCodeName: [{
						required: true,
						message: '请选择开户支行',
						trigger: ['change', 'blur'],
					}],
					openAccBank: [{
						required: true,
						message: '请输入开户支行',
						trigger: ['change', 'blur'],
					}],
					accountName: [{
						required: true,
						message: '请输入账户名',
						trigger: ['change', 'blur'],
					}],
					bankCode: [{
						required: true,
						message: '请输入银行行号',
						trigger: ['change', 'blur'],
					}],
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							pattern: /^1\d{10}$/,
							message: '手机号格式不正确',
							trigger: 'change'
						}
					],
					msgCode: [{
						required: true,
						message: '请输入验证码',
						trigger: ['change', 'blur'],
					}],
				},
				VerCodeStr: "获取验证码",
				VerCodeNum: 60,
				VerCodeIntervalObj: null,
				list: [{
					adCode: "",
					localName: "请选择",
					children: [],
				}, ],
			};
		},
		onReady() {
			if (this.isEdit) {
				this.$refs.uForm.setRules(this.rules);
			}
		},
		mounted() {
			// this.isEdit = true
			this.getBankCardInfo()
		},
		methods: {
			// 显示三级地址联动
			showPicker() {
				this.$refs.cityPicker.show();
			},
			// 三级地址联动回调
			getpickerParentValue(e) {
				console.log(e)
				// // 将需要绑定的地址设置为空，并赋值
				// this.form.consigneeAddressIdPath = [];
				// this.form.consigneeAddressPath = [];
				this.form.adCode = e.map(item => item.adCode)
				let name = "";
				e.forEach((item, index) => {
					if (item.id) {
						// 遍历数据
						// this.form.consigneeAddressIdPath.push(item.id);
						// this.form.consigneeAddressPath.push(item.localName);
						name += item.localName;
						this.form.adCodeName = name;
					}
					if (index == e.length - 1) {
						//如果是最后一个
						let _town = item.children.filter((_child) => {
							return _child.id == item.id;
						});

						this.form.lat = _town[0].center.split(",")[1];
						this.form.lon = _town[0].center.split(",")[0];
					}
				});
				this.form.adCodeName = name
				console.log(this.form.adCodeName, '*/*/*/*/*/*/*/*')
			},
			// 获取银行卡信息
			getBankCardInfo() {
				getBankCard().then((res) => {
					if (res.statusCode == 200 && res.data.result && res.data.result.length > 0) {
						this.bankCardObj = res.data.result[0]
					} else {
						this.bankCardObj = null
						this.isEdit = true
						this.reset()
						setTimeout(() => {
							this.$refs.uForm.setRules(this.rules);
						}, 0)
					}
				});
			},
			// 拍照银行卡
			handleCamera() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera'], //从相册选择
					success: (res) => {
						this.uploadTheImg(res.tempFilePaths[0])
					}
				});
			},
			// 图片上传服务器并识别银行卡号
			uploadTheImg(imgFile, operateType, fileName) {
				let Token = storage.getAccessToken()
				let that = this
				uni.uploadFile({
					url: api.common + '/upload/file',
					fileType: "image",
					filePath: imgFile,
					name: 'file',
					ruleForm: {},
					'content-type': 'multipart/form-data',
					header: {
						accessToken: Token,
						'content-type': 'multipart/form-data'
					}, // 设置请求的 header
					success: res => {
						let data = JSON.parse(res.data)
						if (data.code === 200) {
							distinguishBankCard({
								url: data.result
							}).then(info => {
								if (info.data.code === 200) {
									that.form.bankName = info.data.result.bankName
									that.form.cardNo = info.data.result.cardNo
									setTimeout(() => {
										this.$refs.uForm.validate()
									}, 0)
								}
							})
						}
					},
					fail: () => {
						uni.showToast({
							title: "上传失败",
							duration: 2000,
							icon: "none",
						});
					}
				})
			},
			handleVerCode() {
				if (this.form.mobile && /^1\d{10}$/.test(this.form.mobile)) {
					sendVerCode({
						verificationEnums: "BANK_VERIFY", //BANK_VERIFY:银行卡验证；WALLET_PASSWORD：支付密码验证
						mobile: this.form.mobile
					}).then(res => {
						if (res.statusCode == 200) {
							uni.showToast({
								title: res.message,
								duration: 2000,
								icon: "none",
							});
							this.VerCodeIntervalObj = setInterval(() => {
								this.VerCodeNum--
								if (this.VerCodeNum < 0) {
									this.VerCodeStr = "获取验证码"
									this.VerCodeNum = 60
									clearInterval(this.VerCodeIntervalObj)
									this.VerCodeIntervalObj = null
								} else {
									this.VerCodeStr = this.VerCodeNum + "s"
								}
							}, 1000)
						}
					})
				} else {
					uni.showToast({
						title: "请输入正确的手机号",
						duration: 2000,
						icon: "none",
					});
				}
			},
			handleEdit() {
				this.isEdit = true
				this.form = {
					...this.form,
					...this.bankCardObj
				}
				setTimeout(() => {
					this.$refs.uForm.setRules(this.rules);
				}, 0)
			},
			save() {
				console.log(this.form, '=-=-=-=-=-=-')
				this.form.adCode = this.form.adCode.toString()
				this.$refs.uForm.validate(valid => {
					if (valid) {
						saveBankCard(this.form).then(res => {
							if (res.data.code === 200) {
								uni.showToast({
									title: "保存成功",
									duration: 2000,
									icon: "none",
								});
								this.isEdit = false;
								this.getBankCardInfo()
								this.reset()
								if (this.VerCodeIntervalObj) {
									this.VerCodeStr = "获取验证码"
									this.VerCodeNum = 60
									clearInterval(this.VerCodeIntervalObj)
									this.VerCodeIntervalObj = null
								}
							}
						})

					}
				});
			},
			reset() {
				this.form = {
					bankName: "",
					cardNo: "",
					openAccBank: "",
					accountName: "",
					mobile: "",
					msgCode: "",
					adCode: '', //省市区的code
					adCodeName: '', //省市区对应的名称
					bankCode: '', //银行行号
				}
			},
			handleDel() {
				if (this.bankCardObj && this.bankCardObj.id) {
					delBankCard({
						bankId: this.bankCardObj.id
					}).then(res => {
						if (res.data.code) {
							uni.showToast({
								title: "删除成功",
								duration: 2000,
								icon: "none",
							});

							this.getBankCardInfo()
						}
					})
				}
			}
		},
	}
</script>

<style lang="less" scoped>
	.bank-card {
		padding: 20rpx 0;

		.bank-card-detail {
			background: url(https://rsyl.oss-cn-beijing.aliyuncs.com/0c1f48d8a2df4a6abb57599bd0bbed33.png) no-repeat;
			background-size: 100% 100%;
			padding: 32rpx 48rpx;
			position: relative;

			.nameBox {
				display: flex;
				justify-content: space-between;
				color: #FFFFFF;
				font-size: 40rpx;
				font-weight: 400;
				padding: 15rpx 0 0 0;
				box-sizing: border-box;
				align-items: center;

				.user-name {
					margin-right: 10rpx;
				}
			}

			.detail-item {
				display: flex;
				justify-content: space-between;
				color: #FFFFFF;
				font-size: 28rpx;
				font-weight: 400;
				padding: 15rpx 0 0 0;
				box-sizing: border-box;
				align-items: center;

				.item-left {
					font-size: 28rpx;
				}

				.item-right {
					font-size: 30rpx;
					display: flex;
					justify-content: space-around;
					padding: 10rpx 28rpx;
					background: rgba(255, 255, 255, .29);
					border-radius: 38rpx;

					.user-name {
						margin-right: 10rpx;
					}
				}
			}

			.detail-item.last-item {
				margin-top: 8rpx;
			}

			.detail-edit {
				position: absolute;
				top: 50rpx;
				right: 40rpx;
				color: rgba(255, 230, 120, 1);
				font-size: 28rpx;
				font-weight: 400;
			}
		}

		.bank-card-add {
			/deep/.u-form-item {
				background: #FFFFFF;
				margin-bottom: 12rpx;
				padding: 0 20rpx 0 40rpx;

				.u-form-item--right__content__slot {
					display: flex;
					justify-content: space-between;

				}

				.u-form-item__message {
					margin: 12rpx 0;
				}
			}

			.ver-btn {
				color: rgba(16, 230, 45, 1);
				font-size: 24rpx;
				font-weight: 400;
				flex-shrink: 0;
			}

			.detail-save {
				width: 80%;
				height: 76rpx;
				text-align: center;
				line-height: 76rpx;
				color: #FFFFFF;
				font-size: 28rpx;
				font-weight: 400;
				background: linear-gradient(162.65deg, rgba(0, 162, 255, 1) 0%, rgba(22, 111, 219, 0.65) 100%);
				border-radius: 46rpx;
				position: fixed;
				bottom: 40rpx;
				left: 50%;
				transform: translateX(-50%);
			}
		}
	}
</style>
